﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Business;
using System.Text;
using NHibernate.Criterion;
using NHibernate;
using System.Collections;
using ZLCMS.Data.Model;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Business.Config;
using Newtonsoft.Json;
using ZLCMS.Business.Util;
using DotNet.Common.NHibernateUtil;
using System.IO;
using ZLCMS.Business.WeixinService.Data;

namespace ZLCMS.Web.SystemManage.weixin
{
    public partial class ApplyLStatList : System.Web.UI.Page
    {
        protected FrameHelper _framePage;

        protected string _userAccount;
        protected WxApplyConfig _applyDb;
        protected List<WxApplyConfigItem> _itemList;

        protected int _winCount, _useCount;

        protected string _isuse;
        protected string _uid;
        protected string _datebegin;
        protected string _dateend;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            //初始化全局变量值
            InitializeGlobalValue();

            if (!string.IsNullOrEmpty(Request["exportexcel"]))
            {
                ExportExcel();
            }

            //初始化DWZ分页控件
            _framePage = new FrameHelper(this) { RecordCount = GetListCount() };

            BindList(_framePage.PageIndex, _framePage.PageSize);
        }

        #region 初始化全局变量 -private void InitializeGlobalValue()
        /// <summary>
        /// 初始化全局变量
        /// </summary>
        private void InitializeGlobalValue()
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            //初始化全局变量值
            _uid = Request["s_id"] == null ? "" : Request["s_id"];
            _datebegin = Request["datebegin"] == null ? "" : Request["datebegin"];
            _dateend = Request["dateend"] == null ? "" : Request["dateend"];
            _isuse = Request["isuse"] == null ? "" : Request["isuse"];

            tb_s_id.Text = _uid;
            tb_search_datebegin.Text = _datebegin;
            tb_search_dateend.Text = _dateend;

            ParamKit.Bind("YesNo_10", ddl_isuse, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, null, "-1", "-1");
            ddl_isuse.SelectedValue = _isuse;
        } 
        #endregion

        #region 填充网格数据 - protected void BindList(int pageIndex, int pageSize)
        /// <summary>
        /// 填充网格数据
        /// </summary>
        /// <param name="pageIndex">分页索引</param>
        /// <param name="pageSize">分页大小</param>
        protected void BindList(int pageIndex, int pageSize)
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                try
                {         
                    //初始预约报名对象
                    _applyDb = session.CreateCriteria<WxApplyConfig>().Add(Expression.Eq("Id", int.Parse(_uid))).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxApplyConfig>();

                    if (_applyDb == null)
                    {
                        throw new Exception("找不到对应信息.");
                    }

                    _itemList = new List<WxApplyConfigItem>();
                    _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem1 == null ? "" : _applyDb.ApplyItem1));
                    _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem2 == null ? "" : _applyDb.ApplyItem2));
                    _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem3 == null ? "" : _applyDb.ApplyItem3));
                    _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem4 == null ? "" : _applyDb.ApplyItem4));
                    _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem5 == null ? "" : _applyDb.ApplyItem5));
                    _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem6 == null ? "" : _applyDb.ApplyItem6));
                    _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem7 == null ? "" : _applyDb.ApplyItem7));
                    _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem8 == null ? "" : _applyDb.ApplyItem8));
                    _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem9 == null ? "" : _applyDb.ApplyItem9));
                    _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem10 == null ? "" : _applyDb.ApplyItem10));

                    //初始化用户配置对象
                    ICriteria criteria = session.CreateCriteria<WxApplyLog>();
                    SetupCondition(ref criteria);
                    grid.DataSource = criteria.AddOrder(Order.Desc("OptDate")).SetFirstResult((pageIndex - 1) * pageSize).SetMaxResults(pageSize).List();
                    grid.DataBind();
                }
                catch (System.Exception ex)
                {
                    _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }
        } 
        #endregion

        #region 填充查询条件 + private void SetupCondition(ref ICriteria criteria)
        /// <summary>
        /// 填充查询条件
        /// </summary>
        /// <param name="criteria"></param>
        private void SetupCondition(ref ICriteria criteria)
        {
            criteria.Add(Expression.Eq("OwnerAccount", _userAccount));
            criteria.Add(Expression.Eq("ApplyId", int.Parse(_uid)));

            if (!string.IsNullOrEmpty(_datebegin))
            {
                criteria.Add(Expression.Gt("OptDate", DateTime.Parse(_datebegin)));
            }
            if (!string.IsNullOrEmpty(_dateend))
            {
                criteria.Add(Expression.Lt("OptDate", DateTime.Parse(_dateend)));
            }
            if (_isuse.Trim() != "-1" && !string.IsNullOrEmpty(_isuse))
            {
                criteria.Add(Expression.Eq("Status", _isuse));
            }
        } 
        #endregion

        #region 查询数据总数 + protected int GetListCount()
        /// <summary>
        /// 查询数据总数
        /// </summary>
        /// <returns></returns>
        protected int GetListCount()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                ICriteria criteria = session.CreateCriteria<WxApplyLog>();
                SetupCondition(ref criteria);
                object obj = criteria.SetProjection(Projections.RowCount()).UniqueResult();
                return int.Parse(obj.ToString());
            }
        } 
        #endregion


        protected void ExportExcel()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                //初始预约报名对象
                _applyDb = session.CreateCriteria<WxApplyConfig>().Add(Expression.Eq("Id", int.Parse(_uid))).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxApplyConfig>();

                if (_applyDb == null)
                {
                    throw new Exception("找不到对应信息.");
                }

                _itemList = new List<WxApplyConfigItem>();
                _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem1 == null ? "" : _applyDb.ApplyItem1));
                _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem2 == null ? "" : _applyDb.ApplyItem2));
                _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem3 == null ? "" : _applyDb.ApplyItem3));
                _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem4 == null ? "" : _applyDb.ApplyItem4));
                _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem5 == null ? "" : _applyDb.ApplyItem5));
                _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem6 == null ? "" : _applyDb.ApplyItem6));
                _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem7 == null ? "" : _applyDb.ApplyItem7));
                _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem8 == null ? "" : _applyDb.ApplyItem8));
                _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem9 == null ? "" : _applyDb.ApplyItem9));
                _itemList.Add(JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem10 == null ? "" : _applyDb.ApplyItem10));

                //初始化用户配置对象
                ICriteria criteria = session.CreateCriteria<WxApplyLog>();
                SetupCondition(ref criteria);
                IList<WxApplyLog> list = criteria.AddOrder(Order.Desc("OptDate")).List<WxApplyLog>();

                StringBuilder builder = new StringBuilder();
                StringWriter sw = new StringWriter();

                foreach (WxApplyConfigItem item in _itemList)
                {
                    if (item.IsAvailable=="1")
                    {
                        builder.Append(item.Title+"\t");
                    }
                }
                builder.Append("登记时间\t");
                sw.WriteLine(builder.ToString());

                foreach (WxApplyLog item in list)
                {
                    builder.Clear();
                    if (_itemList[0].IsAvailable == "1")
                    {
                        builder.Append(item.ApplyItem1 + "\t");
                    }
                    if (_itemList[1].IsAvailable == "1")
                    {
                        builder.Append(item.ApplyItem2 + "\t");
                    }
                    if (_itemList[2].IsAvailable == "1")
                    {
                        builder.Append(item.ApplyItem3 + "\t");
                    }
                    if (_itemList[3].IsAvailable == "1")
                    {
                        builder.Append(item.ApplyItem4 + "\t");
                    }
                    if (_itemList[4].IsAvailable == "1")
                    {
                        builder.Append(item.ApplyItem5 + "\t");
                    }
                    if (_itemList[5].IsAvailable == "1")
                    {
                        builder.Append(item.ApplyItem6 + "\t");
                    }
                    if (_itemList[6].IsAvailable == "1")
                    {
                        builder.Append(item.ApplyItem7 + "\t");
                    }
                    if (_itemList[7].IsAvailable == "1")
                    {
                        builder.Append(item.ApplyItem8 + "\t");
                    }
                    if (_itemList[8].IsAvailable == "1")
                    {
                        builder.Append(item.ApplyItem9 + "\t");
                    }
                    if (_itemList[9].IsAvailable == "1")
                    {
                        builder.Append(item.ApplyItem10 + "\t");
                    }
                    builder.Append(item.OptDate + "\t");
                    sw.WriteLine(builder.ToString());
                }
                sw.Close();

                OutputKit.OutputExcel(Response, sw);
            }
        }
    }
}